package com.extJs.demo.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet(name = "GetByNameServlet", urlPatterns = "/getByNameServlet")
public class GetByNameServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static DataService ds = new DataService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userName = req.getParameter("userName");
		int start = Integer.valueOf(req.getParameter("start"));
		int limit = Integer.valueOf(req.getParameter("limit"));
		List<User> users = ds.getUsersByName(userName);
		List<User> list = new ArrayList<User>();
		JSONArray ja;

		int userSize = users.size() - start;
		if (userSize >= limit) {
			list = users.subList(start, start + limit);
		} else {
			list = users.subList(start, userSize + start);
		}
		ja = JSONArray.fromObject(list);
		JSONObject jo = new JSONObject();
		jo.put("datas", jo);
		jo.put("total", users.size());
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().print(jo);
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
}
